package com.wh.wisdomsite.xbox.utils.encrypt.hmacSHA1;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Administrator on 2017/3/15.
 */
public class HmacSHA1 {

    /**
     * HmacSHA1加密
     * @param baseString
     * @param keyString
     * @return
     */
    public static String Encrypt(String baseString, String keyString) {
        byte[] keyBytes = keyString.getBytes();
        SecretKey secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(secretKey);
            byte[] text = baseString.getBytes("UTF-8");
            return bytesToHexString(mac.doFinal(text)).trim();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * bytes转16进制
     * @param src
     * @return
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

}
